/*
 * Copyright © Stéphane Raimbault <stephane.raimbault@gmail.com>
 *
 * SPDX-License-Identifier: BSD-3-Clause
 */

#include <errno.h>
#include <modbus.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <pthread.h>
#include <sys/epoll.h>
#include <sys/time.h>
#include <signal.h>

#include "modbus_ipc.h"

#ifndef MSG_NOSIGNAL
# define MSG_NOSIGNAL 0
#endif

#define SERVER_ID 17
#define REGISTERS_START 1000
#define REGISTERS_END 8100
#define REGISTERS_NUM (REGISTERS_END - REGISTERS_START + 1)

enum {
    TCP,
    TCP_PI,
    RTU,
    RS485
};

static modbus_t *ctx;
static pthread_t modify_thread;
static modbus_mapping_t *mb_mapping = NULL;
static int exit_flag = 1;

static void signal_handler(int sig)
{
    exit_flag = 0;
    printf("Exit:%d \n", exit_flag);
}

static void *modify_register_handler(void *param)
{
    int addr = 0;
    int value = 0;
    int start_registers = 0;
    int num = 0;

    start_registers = mb_mapping->start_registers;
    num = mb_mapping->nb_registers;
    while(exit_flag) {
        printf("Plese input addr:");
        scanf("%d", &addr);
        printf("Please input Value:");
        scanf("%d", &value);

        if ((addr < start_registers) || (addr > (start_registers + num))) {
            printf("ERROR:Input error parameter\n");
            continue;
        }

        if (mb_mapping->tab_registers == NULL) {
            printf("Exist\n");
            break;
        }
        printf("addr:%d old_value:%d new_value:%d\n", addr, mb_mapping->tab_registers[addr - start_registers], value);
        mb_mapping->tab_registers[addr - start_registers] = (uint16_t)value;
        
        sleep(1);
    }
    printf("Exit modify register thread\n");
    pthread_exit(&addr);
}

static int modify_register_thread(void)
{
    int ret = 0;
    ret = pthread_create(&modify_thread, NULL, modify_register_handler, (void *)(&ret));
    if(ret != 0) {
        perror("thread create");
        ret = -1;
    }
    return ret;
}

int main(int argc, char *argv[])
{
    int s = -1;
    int rc;
    int use_backend;
    uint8_t *query;
    char *ip_or_device;

    if (argc > 1) {
        if (strcmp(argv[1], "tcp") == 0) {
            use_backend = TCP;
        } else if (strcmp(argv[1], "tcppi") == 0) {
            use_backend = TCP_PI;
        } else if (strcmp(argv[1], "rtu") == 0) {
            use_backend = RTU;
        }  else if (strcmp(argv[1], "rs485") == 0) {
            use_backend = RS485;
        }
        else {
            printf("Modbus server for unit testing.\n");
            printf("Usage:\n  %s [tcp|tcppi|rtu] [<ip or device>]\n", argv[0]);
            printf("Eg. tcp 127.0.0.1 or rtu /dev/ttyUSB0\n\n");
            return -1;
        }
    } else {
        /* By default */
        use_backend = TCP;
    }

    if (argc > 2) {
        ip_or_device = argv[2];
    } else {
        switch (use_backend) {
        case TCP:
            ip_or_device = "127.0.0.1";
            break;
        case TCP_PI:
            ip_or_device = "::1";
            break;
        case RTU:
            ip_or_device = argv[2];
        case RS485:
            ip_or_device = argv[2];
            break;
        default:
            break;
        }
    }

    if (use_backend == TCP) {
        ctx = modbus_new_tcp(ip_or_device, 1502);
        query = malloc(MODBUS_TCP_MAX_ADU_LENGTH);
    } else if (use_backend == TCP_PI) {
        ctx = modbus_new_tcp_pi(ip_or_device, "1502");
        query = malloc(MODBUS_TCP_MAX_ADU_LENGTH);
    } else if (use_backend == RS485) {
        ctx = modbus_new_rtu_rs485(ip_or_device, 9600, 'N', 8, 1);
        modbus_set_slave(ctx, SERVER_ID);
        query = malloc(MODBUS_RTU_MAX_ADU_LENGTH);
    } else {
        ctx = modbus_new_rtu(ip_or_device, 9600, 'N', 8, 1);
        modbus_set_slave(ctx, SERVER_ID);
        query = malloc(MODBUS_RTU_MAX_ADU_LENGTH);
    }

    //modbus_set_debug(ctx, TRUE);

    mb_mapping = modbus_mapping_new_start_address(0, 0, 0, 0, REGISTERS_START, REGISTERS_NUM, 0, 0);
    if (mb_mapping == NULL) {
        fprintf(stderr, "Failed to allocate the mapping: %s\n", modbus_strerror(errno));
        modbus_free(ctx);
        return -1;
    }


    if (use_backend == TCP) {
        s = modbus_tcp_listen(ctx, 1);
        modbus_tcp_accept(ctx, &s);
    } else if (use_backend == TCP_PI) {
        s = modbus_tcp_pi_listen(ctx, 1);
        modbus_tcp_pi_accept(ctx, &s);
    } else {
        rc = modbus_connect(ctx);
        if (rc == -1) {
            fprintf(stderr, "Unable to connect %s\n", modbus_strerror(errno));
            modbus_free(ctx);
            return -1;
        }
    }
    signal(SIGINT, signal_handler);
    modify_register_thread();
    while(exit_flag) {
        do {
            rc = modbus_receive(ctx, query);
        } while (rc == 0);
        if (rc == -1 && errno != EMBBADCRC) {
            break;
        }
        usleep(100000);
        rc = modbus_reply(ctx, query, rc, mb_mapping);
        if (rc == -1) {
            break;
        }
    }

    printf("Quit the loop: %s\n", modbus_strerror(errno));

    if (use_backend == TCP) {
        if (s != -1) {
            close(s);
        }
    }
    modbus_mapping_free(mb_mapping);
    free(query);
    /* For RTU */
    modbus_close(ctx);
    modbus_free(ctx);

    return 0;
}
